import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';
import { createPaginationResponse, parsePaginationParams } from '@/lib/pagination';
import { successResponse, errorResponse } from '@/lib/response';
import { Prisma } from '@prisma/client';

// POST /api/admin/friendly-links/page - 获取友情链接分页列表
async function handler(req: NextRequest) {
  const authResult = await authenticateRequest(req);
  if (!authResult.success) {
    return errorResponse(authResult.error || '身份验证失败');
  }

  const body = await req.json();
  const { page, pageSize, skip } = parsePaginationParams(body);
  const { name, isActive } = body as { name?: string; isActive?: number };

  const where: Prisma.FriendlyLinkWhereInput = {};
  if (name) {
    where.name = { contains: name };
  }
  if (isActive !== undefined) {
    where.isActive = isActive;
  }

  const [items, total] = await Promise.all([
    prisma.friendlyLink.findMany({
      where,
      orderBy: [
        { order: 'asc' },
        { createdAt: 'desc' },
      ],
      skip,
      take: pageSize,
    }),
    prisma.friendlyLink.count({ where }),
  ]);

  const data = items.map((item) => ({
    ...item,
    createdAt: item.createdAt.toISOString(),
    updatedAt: item.updatedAt.toISOString(),
  }));

  const pageResp = createPaginationResponse(data, total, page, pageSize);
  return successResponse(pageResp);
}

export const POST = withMiddleware(handler);